import React, { useEffect } from 'react'
import { Modal, Form, Input, InputNumber, Select, Upload, message, Row, Col, Button } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import type { UploadProps } from 'antd'
import { createProduct, updateProduct, uploadProductImage } from '@/api/product'

// 定义产品接口
interface ProductType {
  id?: number
  teamId?: number
  categoryId?: number
  productTypeId?: number
  productName: string
  sku: string
  specification: string
  purchasePrice: number
  sellingPrice: number
  stockAlert: number
  weight: number
  brand: string
  model: string
  englishName: string
  customsCode: string
  declaredPrice: number
  length: number
  width: number
  height: number
  status: number
  notes: string
  photo?: string
}

// 定义组件Props
interface ProductAddDialogProps {
  visible: boolean
  product: ProductType | null
  onOk: () => void
  onCancel: () => void
}

const ProductAddDialog: React.FC<ProductAddDialogProps> = ({
  visible,
  product,
  onOk,
  onCancel
}) => {
  const [form] = Form.useForm()
  const [photoUrl, setPhotoUrl] = React.useState<string>('')
  const isEdit = !!product

  // 初始化表单数据
  useEffect(() => {
    if (product) {
      // 编辑模式，填充表单数据
      form.setFieldsValue({
        ...product,
        // 将分为单位的价格转换为元
        purchasePrice: product.purchasePrice / 100,
        sellingPrice: product.sellingPrice / 100,
        declaredPrice: product.declaredPrice / 100
      })
      if (product.photo) {
        setPhotoUrl(product.photo)
      }
    } else {
      // 添加模式，重置表单
      form.resetFields()
      setPhotoUrl('')
    }
  }, [form, product])

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()
      
      // 将元为单位的价格转换为分
      const formData = {
        ...values,
        purchasePrice: Math.round(values.purchasePrice * 100),
        sellingPrice: Math.round(values.sellingPrice * 100),
        declaredPrice: Math.round(values.declaredPrice * 100),
        photo: photoUrl || ''
      }

      let res
      if (isEdit && product?.id) {
        // 编辑模式
        res = await updateProduct({
          ...formData,
          id: product.id
        })
      } else {
        // 添加模式
        res = await createProduct(formData)
      }

      if (res.isSuc) {
        message.success(isEdit ? '更新成功' : '添加成功')
        onOk()
      } else {
        message.error(res.message || (isEdit ? '更新失败' : '添加失败'))
      }
    } catch (error) {
      console.error('表单验证失败:', error)
    }
  }

  // 图片上传配置
  const uploadProps: UploadProps = {
    name: 'file',
    action: 'http://localhost:23892/api/Products/UploadImage',
    headers: {
      // 如果需要认证，可以在这里添加认证头
    },
    showUploadList: false,

    onChange: async (info) => {
      console.log(info);
      
      if (info.file.status === 'done') {
        if (info.file.response && info.file.response.isSuc) {
          setPhotoUrl(info.file.response.data)
          message.success('图片上传成功')
        } else {
          message.error(info.file.response?.message || '图片上传失败')
        }
      } else if (info.file.status === 'error') {
        message.error('图片上传失败')
      }
    }
  }

  return (
    <Modal
      title={isEdit ? '编辑产品' : '添加产品'}
      open={visible}
      onOk={handleSubmit}
      onCancel={onCancel}
      width={900}
      bodyStyle={{ maxHeight: '600px', overflowY: 'auto' }}
    >
      <Form
        form={form}
        layout="vertical"
      >
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="productName"
              label="产品名称"
              rules={[{ required: true, message: '请输入产品名称' }]}
            >
              <Input placeholder="请输入产品名称" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="sku"
              label="SKU"
              rules={[{ required: true, message: '请输入SKU' }]}
            >
              <Input placeholder="请输入SKU" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="specification"
              label="规格"
              rules={[{ required: true, message: '请输入规格' }]}
            >
              <Input placeholder="请输入规格" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="brand"
              label="品牌"
            >
              <Input placeholder="请输入品牌" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="model"
              label="型号"
            >
              <Input placeholder="请输入型号" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="englishName"
              label="英文名称"
            >
              <Input placeholder="请输入英文名称" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="customsCode"
              label="海关编码"
            >
              <Input placeholder="请输入海关编码" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="purchasePrice"
              label="入库价格(元)"
              rules={[{ required: true, message: '请输入入库价格' }]}
            >
              <InputNumber
                min={0}
                precision={2}
                style={{ width: '100%' }}
                placeholder="请输入入库价格"
              />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="sellingPrice"
              label="出库价格(元)"
              rules={[{ required: true, message: '请输入出库价格' }]}
            >
              <InputNumber
                min={0}
                precision={2}
                style={{ width: '100%' }}
                placeholder="请输入出库价格"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="declaredPrice"
              label="申报价格(元)"
            >
              <InputNumber
                min={0}
                precision={2}
                style={{ width: '100%' }}
                placeholder="请输入申报价格"
              />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="stockAlert"
              label="库存警告值"
            >
              <InputNumber
                min={0}
                style={{ width: '100%' }}
                placeholder="请输入库存警告值"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="weight"
              label="重量(g)"
            >
              <InputNumber
                min={0}
                style={{ width: '100%' }}
                placeholder="请输入重量"
              />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              name="length"
              label="长度(cm)"
            >
              <InputNumber
                min={0}
                style={{ width: '100%' }}
                placeholder="请输入长度"
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="width"
              label="宽度(cm)"
            >
              <InputNumber
                min={0}
                style={{ width: '100%' }}
                placeholder="请输入宽度"
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="height"
              label="高度(cm)"
            >
              <InputNumber
                min={0}
                style={{ width: '100%' }}
                placeholder="请输入高度"
              />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="productTypeId"
              label="产品类型"
            >
              <Select
                placeholder="请选择产品类型"
                options={[
                  { value: 1, label: '普通商品' },
                  { value: 2, label: '组合商品' }
                ]}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="categoryId"
              label="产品分类"
            >
              <Select
                placeholder="请选择产品分类"
                options={[
                  { value: 1, label: '电子产品' },
                  { value: 2, label: '生活用品' },
                  { value: 3, label: '床上用品' }
                ]}
              />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="status"
              label="状态"
              initialValue={1}
            >
              <Select
                placeholder="请选择状态"
                options={[
                  { value: 1, label: '启用' },
                  { value: 0, label: '禁用' }
                ]}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="产品图片"
            >
              <Upload {...uploadProps}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <div>
                    <Button icon={<UploadOutlined />}>上传图片</Button>
                  </div>
                  {photoUrl && (
                    <div style={{ marginLeft: 16 }}>
                      <img 
                        src={`http://localhost:23892${photoUrl}`} 
                        alt="产品图片" 
                        style={{ maxWidth: '100px', maxHeight: '100px' }} 
                      />
                    </div>
                  )}
                </div>
              </Upload>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name="notes"
              label="备注"
            >
              <Input.TextArea rows={3} placeholder="请输入备注" />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  )
}

export default ProductAddDialog